package drds.plus.datanode.configuration;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Weight {

    private static final Pattern weightPattern_r = Pattern.compile("[R](\\d*)");
    private static final Pattern weightPattern_w = Pattern.compile("[W](\\d*)");
    private static final Pattern weightPattern_p = Pattern.compile("[P](\\d*)");
    private static final Pattern weightPattern_q = Pattern.compile("[Q](\\d*)");


    /**
     * 读权重，默认是10
     */
    public final int readWeight;

    /**
     * 写权重，默认是10
     */
    public final int writeWeight;

    /**
     * 读优先级，默认是0
     */
    public final int readPriority;

    /**
     * 写优先级，默认是0
     */
    public final int writePriority;


    public Weight(String weightStr) {
        weightStr = weightStr.trim().toUpperCase();
        // 如果字母'R'在weightStr中找不到，则读权重是0，
        // 如果字母'R'在weightStr中已找到了，但是在字母'R'后面没有数字，是读权重是10
        readWeight = getValue(weightStr, 'R', weightPattern_r, 0, 10);
        writeWeight = getValue(weightStr, 'W', weightPattern_w, 0, 10);
        readPriority = getValue(weightStr, 'P', weightPattern_p, 0, 0);
        writePriority = getValue(weightStr, 'Q', weightPattern_q, 0, 0);
    }

    // 如果字符c在weightStr中找不到，则返回defaultValue1，
    // 如果字符c在weightStr中已经找到了，但是在字母c后面没有数字，则返回defaultValue2,
    // 否则返回字母c后面 的数字.
    private static int getValue(String weightString, char c, Pattern pattern, int defaultValue1, int defaultValue2) {
        if (weightString.indexOf(c) == -1) {
            return defaultValue1;
        } else {
            Matcher matcher = pattern.matcher(weightString);
            matcher.find();
            if (matcher.group(1).length() == 0) {
                return defaultValue2;
            } else {
                return Integer.parseInt(matcher.group(1));
            }
        }
    }


    public String toString() {
        return "Weight[readWeight=" + readWeight + ", writeWeight=" + writeWeight + ", readPriority=" + readPriority + ", writePriority=" + writePriority + "]";
    }
}
